package com.example.actionsignin.utils;

import android.content.Context;
import android.hardware.fingerprint.FingerprintManager;
import android.os.Build;
import android.os.CancellationSignal;


/**
 * 指纹识别
 * Created by 旭 on 2017/11/6/006.
 */

public class FingerprintUtil {

    private Context mContext;
    private static final String TAG = "FingerprintUtil";
    private FingerprintManager fingerprintManager;
    private CancellationSignal cancellationSignal = new CancellationSignal();
    private OnFingerprintListener mOnFingerprintListener;
    private FingerprintManager.AuthenticationCallback callback = new FingerprintManager.AuthenticationCallback() {
        @Override
        public void onAuthenticationError(int errorCode, CharSequence errString) {
            super.onAuthenticationError(errorCode, errString);
//            Log.d(TAG, "onAuthenticationError: " + errString);
            ToastUtil.INSTANCE(mContext, String.valueOf(errString));
        }

        @Override
        public void onAuthenticationHelp(int helpCode, CharSequence helpString) {
            super.onAuthenticationHelp(helpCode, helpString);
//            Log.d(TAG, "onAuthenticationHelp: " + helpString);
            ToastUtil.INSTANCE(mContext, String.valueOf(helpString));
        }

        @Override
        public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
            super.onAuthenticationSucceeded(result);
            ToastUtil.INSTANCE(mContext,"识别成功");
            mOnFingerprintListener.onFingerprint();
        }

        @Override
        public void onAuthenticationFailed() {
            super.onAuthenticationFailed();
            ToastUtil.INSTANCE(mContext,"识别失败");
        }
    };

    public FingerprintUtil(Context context)
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        {
            this.mContext = context;
            fingerprintManager = (FingerprintManager) context.getSystemService(Context.FINGERPRINT_SERVICE);
        }else {
            ToastUtil.INSTANCE(context,"您的手机版本过低，不支持指纹识别");
        }
    }

    public void doFingerPrint()
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            fingerprintManager.authenticate(null,cancellationSignal,0,callback,null);
        }else {
            ToastUtil.INSTANCE(mContext,"您的手机版本过低，不支持指纹识别");
        }
    }

    public void setFingerprintListener(OnFingerprintListener onFingerprintListener)
    {
        this.mOnFingerprintListener = onFingerprintListener;
    }

    public interface OnFingerprintListener
    {
        void onFingerprint();
    }
}
